# -*- coding：utf-8 -*-
# Python2 兼容
from __future__ import print_function, division

"""
测试blueprint 相关rest操作模式，更新操作步骤
主要用于接口数据访问模式
"""
import os
#import face_recognition
from io import BytesIO
import base64
import json
import time
from flask import url_for, redirect, request, abort, jsonify, make_response
from config import Config
from . import apiApp

"""
@apiApp.route('/compare', methods=['GET', 'POST', 'OPTIONS'])
def compare():
    t1 = time.time()
    if request.method == 'POST':
        json_data = request.get_json()
        # print(json_data)
        b64_image_01 = json_data['b64_image_01']
        b64_image_02 = json_data['b64_image_02']

        try:
            distance = compare_face(b64_image_01, b64_image_02)
        except IndexError as err:
            t2 = time.time()
            use_time = str(round(t2-t1, 2)) + 's'
            return jsonify({ "message": "face not found", "distance": "0.0", "use_time": use_time})
        except Exception as err:
            print(err)
            t2 = time.time()
            use_time = str(round(t2-t1, 2)) + 's'
            return jsonify({ "message": "unknow error", "distance": "0.0", "use_time": use_time})

        distance_string = str(round((1-distance[0]) * 100, 2))
        print(json.dumps({ "message": "ok", "distance": distance_string}))
        t2 = time.time()
        use_time = str(round(t2-t1, 2)) + 's'
        resp = make_response(jsonify({ "message": "ok", "distance": distance_string, "use_time": use_time}))
        return resp

    else:
        return '''请使用Post方式传递数据<br><br>'''
"""

@apiApp.route('/search_face', methods=['GET', 'POST', 'OPTIONS'])
def compare():
    t1 = time.time()
    if request.method == 'POST':
        json_data = request.get_json()
        b64_image_01 = json_data['b64_image_01']
        curentname = ''
        try:
            rootDir = Config.RECOGNIZE_FILE
            list = os.listdir(rootDir)
            sextList = ['.png', '.jpg', '.jpeg']
            for i in range(0, len(list)):
                path = os.path.join(rootDir, list[i])   #路径
                (filepath, tempfilename) = os.path.split(filename)        #后缀
                (shotname, extension) = os.path.splitext(tempfilename)
                if os.path.isfile(path) & (extension in sextList):
                    b64_image_02 = BytesIO(base64.b64encode(path))
                    distance = compare_face(b64_image_01, b64_image_02)
                    curentname = shotname
                    print(distance)
        except IndexError as err:
            t2 = time.time()
            use_time = str(round(t2-t1, 2)) + 's'
            return jsonify({ "message": "face not found", "distance": "0.0", "use_time": use_time})
        except Exception as err:
            print(err)
            t2 = time.time()
            use_time = str(round(t2-t1, 2)) + 's'
            return jsonify({ "message": "unknow error", "distance": "0.0", "use_time": use_time})

        distance_string = str(round((1-distance[0]) * 100, 2))
        print(json.dumps({ "message": "ok", "distance": distance_string}))
        t2 = time.time()
        use_time = str(round(t2-t1, 2)) + 's'
        resp = make_response(jsonify({ "message": "ok", "distance": distance_string, "use_time": use_time,
                                       "curentname": curentname}))
        return resp

    else:
        return '''请使用Post方式传递数据<br><br>'''

"""
进行base64压缩后的图像
"""
def compare_face(b64_image_01, b64_image_02):

    bytes_img_01 = BytesIO(base64.b64decode(b64_image_01))
    bytes_img_02 = BytesIO(base64.b64decode(b64_image_02))

    known_image = face_recognition.load_image_file(bytes_img_01)
    unknown_image = face_recognition.load_image_file(bytes_img_02)

    known_encoding = face_recognition.face_encodings(known_image)[0]
    unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

    distance = face_recognition.face_distance([known_encoding], unknown_encoding)
    return distance

